var express = require('express')
const crypto = require('crypto')
let Runtime = require('../runtime')
var router = express.Router()
var log = Runtime.App.Log.helper
let HttpClient = Runtime.App.HttpClient
let config = Runtime.App.AppConfig.runtime.sso

let SessionStore = Runtime.SessionStore

let Modules = require('../modules')

let redirectLogin = (req, res) => {
  let query = []
  for (let i in req.query) {
    if (i === 'code')
      continue
    query.push(i + '=' + req.query[i])
  }
  let url = req.originalUrl.indexOf('?') > -1 ? (req.originalUrl.split('?')[0] + '?' + query.join('&')) : req.originalUrl
  res.redirect(config.host + '?redirectUrl=' + encodeURIComponent('http://' + req.headers.host + url))
}

router.get('/*', function (req, res, next) {
  let lang = req.query.lang || 'zh-CN'
  res.cookie('lang', lang, {
    maxAge: 1000 * 3600 * 24 * 7,
    httpOnly: true
  })
  res.setLocale(lang)
  next()
})

function md5Sign() {
  let args = Array.prototype.slice.call(arguments, 0)
  let source = ''
  args.forEach(item => {
    source += item
  })
  source = source + config.md5
  const hash = crypto.createHash('md5')
  hash.update(source)
  return hash.digest('hex')
}

function saveSession(req, data) {
  SessionStore.setAccessInfo(req, {
    accessToken: data.accessToken,
    expiresIn: data.expiresIn,
    refreshToken: data.refreshToken
  })
  SessionStore.setUserId(req, data.userCode)
  SessionStore.setUserCode(req, data.userCode)
  SessionStore.setUserName(req, data.userName)
  SessionStore.setSessionId(req, data.sessionId)
}

/**
 * 首页路由规则：
 * 1.先判断URL是否存在Code，如果存在code则去验证code
 * 2.如果不存在code，则验证Session中是否存在Token，如果存在Token，则表示已登录，如果不存在Token，则表示登录已过期，跳转到CAAS登录页面
 * 第二次判断是否系统间跳转，如果是跳转过来的，则更新当前的Session数据。如果不是系统间跳转，则进入后续的逻辑判断
 */

//验证是否AUTH_CODE授权登陆
router.get('/', function (req, res, next) {
  let code = req.query.code
  if (code) {
    Modules.sso.getTokenAsync(code)
      .then(responseData => {
        log.info(responseData)
        if (responseData && responseData.success) {
          saveSession(req, responseData.data)


          Modules.javaSever.getMenuList().then(permission => {
            if (permission && permission.success) {
              let resourcesObj = {}
              let operationsObj = {}
              permission.data.map(m => {
                resourcesObj[m.name] = m.name
              })

              Modules.sso.getUserResourcesAsync(responseData.data.sessionId, responseData.data.accessToken, resourcesObj, operationsObj)
                .then(permission => {
                  if (permission && permission.success) {
                    console.log('lxf>>>',resourcesObj)
                    console.log('lxf<<<',permission)
                    SessionStore.setUserResource(req, permission.data)
                  } else {
                    log.warn('没有获取到权限信息')
                  }
                  res.redirect('/')
                })
                .catch(ex => {
                  log.warn(ex)
                  redirectLogin(req, res)
                })

            } else {
              log.warn('获取系统应用列表错误：', permission)
            }
          })
            .catch(ex => {
              log.warn(ex)
            })
        } else {
          log.warn(responseData.msg || '')
          redirectLogin(req, res)
        }
      })
  } else {
    next()
  }
})

/*//验证是否系统间跳转
 router.get('/', function(req, res, next) {
 let sid = req.query.s
 let token = req.query.t
 let sign = req.query.sign
 if (sid || token || sign) {
 //三个字段缺一不可，sign必须是SID+TOKEN的加密
 if (!(sid && token && sign) || sign !== md5Sign(sid, token)) {
 redirectLogin(req, res)
 return
 }

 //检测Session是否有效
 //如果有效，则更新当前Session为获取到的Session信息
 Modules.sso.checkSessionAsync(sid, token)
 .then(result => {
 if (result && result.success) {
 return Modules.sso.getUserResourcesAsync(result.data.sessionId, result.data.accessToken)
 .then(permission => {
 if (permission && permission.success) {
 saveSession(req, result.data)
 SessionStore.setUserResource(req, permission.data)
 res.redirect('/')
 } else {
 log.warn(permission)
 redirectLogin(req, res)
 }
 })
 .catch(ex => {
 log.warn(ex)
 redirectLogin(req, res)
 })
 } else {
 SessionStore.clearSession(req)
 redirectLogin(req, res)
 }
 })
 .catch(ex => {
 log.error(ex)
 redirectLogin(req, res)
 })
 } else {
 next()
 }
 }) */

router.get('/', function (req, res, next) {
  console.log(req.sessionID)
  //验证是否本地的Session有效
  if (!(SessionStore.getAccessInfo(req) && SessionStore.getSessionId(req))) {
    // 验证Token是否有效
    redirectLogin(req, res)
    return
  }
  let sid = SessionStore.getSessionId(req)
  let token = SessionStore.getAccessInfo(req).accessToken
  Modules.sso.checkSessionAsync(sid, token)
    .then(result => {
      console.log(result)
      if (result && result.success) {
        let userName = SessionStore.getUserName(req)
        let resources = SessionStore.getUserResource(req)
        res.render('index', {
          userName: userName,
          loginUrl: config.host,
          remoteHost: Runtime.App.AppConfig.app.remoteHost,
          resources: resources,
          apmHost: Runtime.App.AppConfig.app.apmHost
        })
      } else {
        SessionStore.clearSession(req)
        redirectLogin(req, res)
      }
    })
    .catch(ex => {
      log.error(ex)
      redirectLogin(req, res)
    })
})

module.exports = router
